# Copyright (c) 2011 anatanokeitai.com(sakurai_youhei)
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# 
# The Software shall be used for Younger than you, not Older.
# 

from pyacd.connection import gen_httplib_conn
from pyacd.connection import Connection as OriginalConnection

import sys
import urllib2

import pyacp
from pyacp.exception import PyAmazonCloudPlayerError


class Connection(OriginalConnection):
  def _do_request(self,method,url,body,headers):
    """
    return response string
    """
    if not (method=="GET" or method=="POST" or method=="PUT" or method=="DELETE"):
      raise PyAmazonCloudPlayerError("unsupported method %s"%method)

    if not self.session:
      raise PyAmazonCloudPlayerError("session is None.")
    elif not self.session.is_valid():
      raise PyAmazonCloudPlayerError("session is invalid. %s"%self.session)

    scheme,host = urllib2.urlparse.urlparse(url)[:2]

    conn=gen_httplib_conn(scheme,host)

    hs={"Cookie":"; ".join( ["=".join(i) for i in self.session.cookies.items()] )}
    if self.session.cookies.get("session-id"):
      hs["x-amzn-SessionId"]=self.session.cookies.get("session-id")

    hs["x-adp-token"]=self.session.token_id
#    hs["X-Requested-With"]="XMLHttpRequest"
#    hs["RequestId"]="a9aadd36-eb9e-dmcp-c972-7b23231cf028"

    if headers:
      hs.update(headers)

    path = url.split(host,1)[1]
    conn.request(method,path,body,hs)


#    print method
#    print path
#    print body
#    print hs
#    print "*"*20


    if pyacp.debug_level:
      sys.stderr.write(method)

    resp = conn.getresponse()

#    print resp.getheaders()
#    print "*"*20

    if 400< resp.status <599:
      sys.stderr.write(resp.read())
      raise PyAmazonCloudPlayerError("response code is %d"%resp.status)

    if pyacp.debug_level:
      sys.stderr.write("->")

    if resp.getheader("Set-Cookie"):
      self.session.update_cookies(resp.getheader("Set-Cookie"))

    if resp.getheader("Location"):
      return self.do_get(resp.getheader("Location"))

    resp_body=resp.read()
    #print resp_body
    conn.close()

    return resp_body

